package com.shjn.squirrel.fragment;

import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.shjn.squirrel.R;
import com.shjn.squirrel.application.MyApplication;
import com.shjn.squirrel.bean.httpBean.RecordBean;
import com.shjn.squirrel.bean.httpBean.SaveDeliveryRecordReq;
import com.shjn.squirrel.customView.BackAndTimerView;
import com.shjn.squirrel.model.Constant;
import com.shjn.squirrel.model.LocalStorage;
import com.shjn.squirrel.model.UserInfoCache;
import com.shjn.squirrel.utils.OkhttpHelper;
import com.shjn.squirrel.utils.OrderUtils;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 用户结束投递
 */
public class UserFinishFragment extends BaseFragment implements View.OnClickListener {

    private static UserFinishFragment instance;
    private Button mBtnOVer;
    private Button mBtnLook;
    private RelativeLayout mRelNone;
    private RelativeLayout mRelMoney;
    private RelativeLayout mRelIntegral;
    private RelativeLayout mRelAll;
    private TextView mTVMoney;
    private TextView mTvIntegral;
    private TextView mTvAllMoney;
    private TextView mTvAllIntegral;

    public UserFinishFragment() {
    }

    public synchronized static UserFinishFragment getInstance() {
        if (instance == null) {
            instance = new UserFinishFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return createView(inflater, R.layout.user_deliver_over, container);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initTimer();
        initView();
    }

    /**
     * 初始化倒计时器
     */
    private void initTimer() {
        //加载定时器面板，设置定时时间
        mActivity.mBackAndTimer.setOnBackListener(null).setBackVisibleState(false)
                .setOnTimerFinishListener(new BackAndTimerView.OnTimerFinishListener() {
                    @Override
                    public void onTimerFinish() {
                        //返回到首页
                        if (!UserSelectFragment.getInstance().isAdded()) {
                            UserInfoCache.clearUserInfo();//清空用户信息
                            mActivity.mBackAndTimer.setVisibleState(false);
                            mActivity.getFragmentManager().beginTransaction()
                                    .replace(R.id.mid, UserSelectFragment.getInstance())
                                    .commit();
                            TopFragment.getInstance().mBtnMyRecycler.setVisibility(View.VISIBLE);
                        }
                    }
                }).setTime(60).setVisibleState(true).start();
    }

    /**
     * 初始化相关控件
     */
    private void initView() {
        mRelNone = (RelativeLayout) mView.findViewById(R.id.rel_none);
        mRelMoney = (RelativeLayout) mView.findViewById(R.id.rel_only_money);
        mRelIntegral = (RelativeLayout) mView.findViewById(R.id.rel_only_integral);
        mRelAll = (RelativeLayout) mView.findViewById(R.id.rel_only_all);
        mTVMoney = (TextView) mView.findViewById(R.id.tv_money_value);
        mTvIntegral = (TextView) mView.findViewById(R.id.tv_integral_value);
        mTvAllMoney = (TextView) mView.findViewById(R.id.tv_all_money_value);
        mTvAllIntegral = (TextView) mView.findViewById(R.id.tv_all_integral_value);
        mBtnOVer = (Button) mView.findViewById(R.id.btn_over);
        mBtnLook = (Button) mView.findViewById(R.id.btn_look);
        mBtnOVer.setOnClickListener(this);
        mBtnLook.setOnClickListener(this);
        //判断显示哪种情况
        SpannableString spannableString = null;
        if (UserInfoCache.getTotalMoney() == 0 && UserInfoCache.getTotalIntegral() == 0) {
            //环保金和积分都没有
            mRelNone.setVisibility(View.VISIBLE);

        } else if (UserInfoCache.getTotalMoney() != 0 && UserInfoCache.getTotalIntegral() == 0) {
            //有环保金，没有积分都没有
            spannableString = new SpannableString(String.format("%.2f", UserInfoCache.getTotalMoney()) +
                    " " + "环保金");
            spannableString.setSpan(new RelativeSizeSpan((float) (16 / 20.0)),
                    spannableString.toString().indexOf(" ") + 1, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            mTVMoney.setText(spannableString);
            mRelMoney.setVisibility(View.VISIBLE);

        } else if (UserInfoCache.getTotalMoney() == 0 && UserInfoCache.getTotalIntegral() != 0) {
            //有积分，没有环保金
            spannableString = new SpannableString(String.format("%.0f", UserInfoCache.getTotalIntegral()) +
                    " " + "环保积分");
            spannableString.setSpan(new RelativeSizeSpan((float) (16 / 20.0)),
                    spannableString.toString().indexOf(" ") + 1, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            mTvIntegral.setText(spannableString);
            mRelIntegral.setVisibility(View.VISIBLE);

        } else if (UserInfoCache.getTotalMoney() != 0 && UserInfoCache.getTotalIntegral() != 0) {
            //环保金、积分都有
            spannableString = new SpannableString(String.format("%.0f", UserInfoCache.getTotalIntegral()) +
                    " " + "环保积分");
            spannableString.setSpan(new RelativeSizeSpan((float) (16 / 20.0)),
                    spannableString.toString().indexOf(" ") + 1, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            mTvAllIntegral.setText(spannableString);

            spannableString = new SpannableString(String.format("%.2f", UserInfoCache.getTotalMoney()) +
                    " " + "环保金");
            spannableString.setSpan(new RelativeSizeSpan((float) (16 / 20.0)),
                    spannableString.toString().indexOf(" ") + 1, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            mTvAllMoney.setText(spannableString);
            mRelAll.setVisibility(View.VISIBLE);
        }
        //上传用户投递记录
        ArrayList<RecordBean> record = new ArrayList<>();
        for (String key : UserInfoCache.records.keySet()) {
            if (key.equals(Constant.bottle)) {
                record.add(new RecordBean(Constant.categoryMap.get(key)[3], UserInfoCache.records.get(key).get(1).intValue(), 0));

            } else if (key.equals(Constant.glass) || key.equals(Constant.harm)) {
                record.add(new RecordBean(Constant.categoryMap.get(key)[3], UserInfoCache.records.get(key).get(1).intValue(), UserInfoCache.records.get(key).get(0)));
            } else {
                record.add(new RecordBean(Constant.categoryMap.get(key)[3], 0, UserInfoCache.records.get(key).get(0)));
            }
        }
        Log.i("info", "userSaveRecord_request: " + new SaveDeliveryRecordReq(LocalStorage.getDeviceID(MyApplication.getInstance()),
                UserInfoCache.telNum, OrderUtils.getSerialNumber(), record));
        OkhttpHelper.postRequest(Constant.baseUrl + "machine/delivery/saveRecord",
                new Gson().toJson(new SaveDeliveryRecordReq(LocalStorage.getDeviceID(MyApplication.getInstance()),
                        UserInfoCache.telNum, OrderUtils.getSerialNumber(), record)),
                new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.i("info", "userSaveRecord_onFailure: " + e.getMessage());
                        OkhttpHelper.requestAgain(call, this);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.i("info", "userSaveRecord_response:" + response.body().string());
                    }
                });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //返回首页
            case R.id.btn_over:
                if (!UserSelectFragment.getInstance().isAdded()) {
                    mActivity.mBackAndTimer.stop();
                    UserInfoCache.clearUserInfo();//清空用户信息
                    mActivity.mBackAndTimer.setVisibleState(false);
                    mActivity.getFragmentManager().beginTransaction()
                            .replace(R.id.mid, UserSelectFragment.getInstance())
                            .commit();
                    TopFragment.getInstance().mBtnMyRecycler.setVisibility(View.VISIBLE);
                }
                break;
            //查看废品去向
            case R.id.btn_look:
                if (!WasteDirectionDialog.getInstance().isAdded()) {
                    mActivity.mBackAndTimer.stop();
                    WasteDirectionDialog.getInstance().setOnCloseDialogListener(new BaseDialogFragment.OnCloseDialogListener() {
                        @Override
                        public void onCloseDialog() {
                            mActivity.mBackAndTimer.setTime(mActivity.mBackAndTimer.getCurrentTime()).start();
                        }
                    });
                    WasteDirectionDialog.getInstance().show(mActivity.getFragmentManager(), "user_waste_direction_dialog");
                }
                break;
            default:
                break;
        }
    }
}
